#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:set sts=4:tabstop=4:expandtab:shiftwidth=4:
# EasyUbuntu - Install commonly requested apps on your (k/X)ubuntu box 
# Copyright (C) 2006 EasyUbuntu team
# https://launchpad.net/products/easyubuntu
# http://easyubuntu.freecontrib.org
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
# 
from backend import *
from detect import *
from qt import *
from qtfrontendauto import EasyUbuntuGui
from qtaboutauto import qtabout
from qtwarningauto import QtWarning
import sys
from qtprocess import QtLogger
import commands

from xml.dom import minidom
class eu(EasyUbuntuGui):

    def __init__(self, pkglist, desktop, confdir,  parent=None, name=None, fl=0):
        # Inherit the gui and layout stuff from the autogenerated file
        EasyUbuntuGui.__init__(self,parent,name,fl)
        self.desktop = desktop
        self.pkglist = pkglist
        self.confdir = confdir
        self.preconfiglist = [] #list of commands to be executed before installing a package
        self.packageslist = [] #list of packages to be installed
        self.configslist = []  #list of configuration to be performed
        #self.illegalItems = []

        while aptcheck():
            if self.aptIsRunning():
                sys.exit(1)

        self.tabs.removePage( self.tabs.currentPage())

        catlist = childNodeWithAttrs(self.pkglist,self.desktop)[0]
        for catname in catlist:
            # Create a widget for every category page
            categories = QWidget(self.tabs, str(catname))

            #every <subcat> in the XML is a checkbox in the page
            subcatlist = childNodeWithAttrs(self.pkglist,self.desktop,catname)[0]
            # Add a layout element for every category, can tweak appearance
            layout = QVBoxLayout(categories,5,0,str(catname))
            for subcatname in subcatlist:
                if subcatname != "N/A":
                    desc = childNodeWithAttrs(self.pkglist,self.desktop,catname,subcatname,'label')[0]
                    # create checkbox for every subcategorym and use te desc string

                    checkbox = QCheckBox(desc[0],categories, str(subcatname))
                    self.connect( checkbox, SIGNAL('toggled(bool)'), self.checkboxHandler)
                    layout.addWidget(checkbox)
            layout.addStretch()
            self.tabs.insertTab(categories,catname)
        
    def checkboxHandler(self):
        checkboxlist = self.queryList("QCheckBox")
        self.ok.setEnabled(False)
        for checkbox in checkboxlist:
            if checkbox.isChecked():
                self.ok.setEnabled(True)
                return # As we need to check for only the first set element

    def setupQTDialogHandler(self):
        """
        Setup debconf to use qt dialog instead of readline
        """
        string = "Template: debconf/frontend"
        fileobj = open("/var/cache/debconf/config.dat", 'r')

        count = 0
        for line in fileobj:
            if count:
                break
            if string in line:
                count += 1
        # Now line will have Value: Kde
        frontend = line.split(" ")[-1].strip()
        fileobj.close()

        p1 = subprocess.Popen(['apt-get', 'install', 'libqt-perl']).wait()
        cmd = ['echo', "debconf debconf/frontend select Kde"]
        p1 = subprocess.Popen(cmd, stdout = subprocess.PIPE)
        p1 = subprocess.Popen("debconf-set-selections", stdin = p1.stdout, shell=True)

    def okclicked(self):
        self.setupQTDialogHandler()
        checkboxlist = self.queryList("QCheckBox")
        self.packageslist = []
        self.configslist = []
        self.illegalItems = []
        self.preconfiglist = []

        for checkbox in checkboxlist:
            if checkbox.isChecked():
                catname = checkbox.parent().name()
                subcatname=checkbox.name()
                alert = childNodeWithAttrs(self.pkglist,self.desktop,catname,subcatname,'alert')[0]
                if alert[0] in ["illegal","nonfree"]:
                    desc = childNodeWithAttrs(self.pkglist,self.desktop,catname,subcatname,'label')[0]
                    self.illegalItems.append(desc[0])
                
                for eachpreconfig in childNodeWithAttrs(self.pkglist,self.desktop,catname,subcatname,'preconfig')[0]:
                    self.preconfiglist.append(eachpreconfig)
                for eachpackage in childNodeWithAttrs(self.pkglist,self.desktop,catname,subcatname,'pkg')[0]:
                    self.packageslist.append(eachpackage)
                for eachconfig in childNodeWithAttrs(self.pkglist,self.desktop,catname,subcatname,'config')[0]:
                    self.configslist.append(eachconfig)

        if self.illegalItems:
            warningList = QString("""
You have chosen to install items that 
might be illegal in your country.
Click 'Cancel' to review these items or 
Click 'OK' to install 
Please review the following items:\n\n""")
            for item in self.illegalItems:
                warningList += QString(item + "\n")
            response = QMessageBox.warning(self,QString("Warning"),\
                    warningList, QMessageBox.Cancel, QMessageBox.Ok)
            # response = 2 -> Cancel
            # response = 1 -> OK
            if response == 1:
                w = QtLogger(self.preconfiglist, self.packageslist, self.configslist, self.confdir)
                w.exec_loop()
            else:
                return
        else:
            w = QtLogger(self.preconfiglist, self.packageslist, self.configslist, self.confdir)
            w.exec_loop()


    def aboutclicked(self):
        #self.setEnabled(False)
        w = qtabout()
        w.exec_loop()

    def aptIsRunning(self):
        """
        Dialog which pops up if apt is running
        """
        response = QMessageBox.critical(self,QString("EasyUbuntu Warning"),
                QString(""" 
                A package manager is already running. 
                Please close the package manager and press the OK button. 
                If you would like to use the other package manager, 
                press Cancel to exit EasyUbuntu."""),
                QMessageBox.Cancel, QMessageBox.Ok)
        return response-1
                    
def launcher(datadir, confdir): 
    a = QApplication(sys.argv)
    QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    # This needs to be loaded based on whether breezy or dapper
#    pkglist = minidom.parse(os.path.join(datadir, 'packagelist-%s.xml' % codename()))
    pkglist = minidom.parse(os.path.join(datadir, 'packagelist.xml'))
    w = eu(pkglist, de(), confdir)
    a.setMainWidget(w)
    w.show()
    a.exec_loop()

if __name__ == '__main__':
    confdir = os.path.abspath('../conf')
    datadir = os.path.abspath('..')
    launcher(datadir, confdir)
